#include<iostream>
using namespace std;
#include<unistd.h>
 #include <sys/types.h>
#include <sys/stat.h>
 #include <sys/types.h>
#include <fcntl.h>
#include<fstream>
#include<cstring>


int main()
{
    const char *filename="./testFifo";
    int ret1=access(filename,F_OK);
    if(ret1==-1)
    {
    int ret=mkfifo(filename,0644);
    if(ret==-1)
    {
        perror("mkfifo error:");
        _exit(-1);
    }
    }
    /*创建进程*/
    pid_t pid=fork();
    if(pid<0)
    {

    }
    else if(pid==0)
    {
    /*子进程*/
    int readFd=open(filename,O_RDONLY);
    if(readFd==-1)
    {
        perror("open fifo error:");
        _exit(-1);
    }
       char buf[128]={0};
       int readBytes=0;
       while(1)
       {
        readBytes=read(readFd,buf,sizeof(buf));
         if(readBytes==0)
        {
            break;
        }
        if(readBytes<0)
        {
            perror("read error:");
            _exit(-1);
        }
        buf[readBytes]='\0';
        printf("readBytes=%d,\tbuf=%s\n",readBytes,buf);

       }
    }
    else
    {
    /*父进程*/  
    int writeFd=open(filename,O_WRONLY);
    if(writeFd==-1)
    {
        perror("open fifo error:");
        _exit(-1);
    }
   ifstream ifs;
   /*打开文件*/
   ifs.open("lyric.txt",ios::in|ios::out);
   if(ifs.is_open()==false)
   {
    perror("open lyric error");
    _exit(-1);
   }

   char buffer[128]={0};

    while(ifs.eof()==false)
    {
        ifs.getline(buffer,sizeof(buffer));
        // cout<<"buffer:"<<buffer<<endl;
        /*写到fifo管道文件里*/
        write(writeFd,buffer,strlen(buffer));

        /*清空脏数据*/
        memset(buffer,0,sizeof(buffer));
        sleep(1);
        
    }
    /*关闭歌词文件*/
    ifs.close();


    }
    return 0;
}